# -*- coding:utf-8 -*-


import requests,json,time
from common.config import *
from common.Helper import Helper
from threading import Thread

# /*拼多多订单详情*/ 无需翻页

class PddDetails( object ):

    def __init__(self):

        pass

    # 页面请求

    def requestIndex(self,task):

        resp = {'type': 105, 'msg': '脱敏数据','content':{}}

        # 设置cookie
        header['cookie'] = task['cookie']

        data = {"orderSn":task['order_sn'],"source":"MMS"}

        r = requests.post( url = domain_url['details_url'],headers=header,data=json.dumps(data))

        # print( r.json())

        if r.status_code == 200 and  r.json()['success']:

            note = {"orderSn": task['order_sn']}

            notes = lambda: requests.post(url=domain_url['order_note_url'], headers=header, data=json.dumps(note))

            if notes().status_code == 200:
                n = notes()

                noteInfo = n.json()

                noteList = [ v['note'] for v in noteInfo['result']]

            data = self.parseIndex(r.json()['result'],noteList)

            resp['content']['content'] = task

            resp['content']['data'] = data
            resp['content']['errmsg'] = '任务完成'
            resp['content']['errcode'] = 0
            print( resp )
            content = Helper.changeBase64(json.dumps(resp['content']))

            resp['content'] = content.decode('ascii')



            print('%s`\t脱敏数据任务请求成功'%task['order_sn'])

            return resp

        # 异常情况
        try:
            error = dict(errorCode=r.json()['error_code'],errorMsg=r.json()['error_msg'])

        except:

            error = dict(errorCode=r.json()['errorCode'],errorMsg=r.json()['errorMsg'])


        resp['content']['content'] = task
        resp['content']['errcode'] = error['errorCode']
        resp['content']['errmsg'] = error['errorMsg']
        resp['content']['data'] = {}

        # print( resp )

        content = Helper.changeBase64(json.dumps(resp['content']))
        resp['content'] = content.decode('ascii')

        # print( type(error['errorMsg']))

        print('%s\t脱敏数据任务请求失败,失败原因:%s' % (task['order_sn'],error['errorMsg']))
        # 店铺cookie过期
        # resp['extra'] = {'owner_id':task['owner_id'],'type':99}

        return resp

    # 解析信息
    def parseIndex(self,items,notes):

        # 订单状态 0 异常 1 未发货 2 已发货待签收 3 已签收
        if items['order_status'] == 0:

            order_status = 1

        elif items['order_status'] ==1:

            order_status = 2

        elif items['order_status'] == 2:

            order_status = 3
        else:
            order_status = 3


        data = {
            # 订单号
            'order_sn':items['order_sn'],
            # 店铺id
            'owner_id':items['mall_id'],
            # 订单状态
            'order_status':order_status ,
            # 订单备注
            'remark':notes,
            # 物流公司
            'shipping_name':items['shipping_name'],
            # 买家姓名
            'receiver_name':items['receive_name'],
            #买家电话
            'receiver_mobile':items['buyer_mobile'],
            # 快递单号
            'tracking_number':items['tracking_number'],
            #下单时间
            'created_time':items['order_time']
        }

        print(data)

        return data




if __name__ == '__main__':

    d = PddDetails()

    # task = {
    #
    #     'order_sn': '190919-443411989152788',
    #     'cookie': 'api_uid=rBQR7F1wo5oA8Faxr9j6Ag==; _nano_fp=XpdjnqEonqCYX0TyXC_osJc1EpPkOn2FgQXY2Ism; PASS_ID=1-ctMWVwNHpQAy4szALjjTJcTqx+xS+dNa224U6ymQIwn9v35qcRRo7RTO0qL26kvUoZ44UJ1fIv23fWGUamPQcQ_982621149_43197961; JSESSIONID=3A7E5B28288233E2DDD303984705C092'
    #
    # }

    task = {
        "type": 205,
        "content": {
            "task_id": 373,
            "owner_id": 186716817,
            "order_sn": "190628-026024019091188",
            "cookie": "api_uid=rBQRGV0ufMgJpwYt0e1qAg==; _nano_fp=XpdjXqXxnqEbnpXyXT_g30sJEPJz34pSjjxCPZK3; PASS_ID=1-ZE+f1bJ3r8u/CcF99nKlx0RDdPWZXtIqPLTV1RsBmpezEHN9qbsFzHREgR0rlEDnImhFkAi8co7pzOcpF8ThSw_186716817_29159208; JSESSIONID=B3D79C236B39A5FB8F3BA157ABD12DBA"
        },
        "msg": "脱敏数据任务"
    }

    task = task['content']

    print(d.requestIndex( task ))

    # threads = []
    #
    # for t in range(3):
    #
    #     t = Thread( target=d.main,args=())
    #
    #     t.start()
    #
    #     threads.append( t )
    #
    # for t in threads:
    #
    #     t.join()

